package com.sunhao.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.sunhao.myapplication.utils.FileUtil;
import com.sunhao.myapplication.utils.ToastUtil;

import java.io.File;

public class MainActivity4 extends AppCompatActivity implements View.OnClickListener {

    private EditText name;
    private EditText age;
    private EditText height;
    private EditText weight;
    private Button save;
    private Button read;
    private CheckBox married;
    private String path;
    private TextView tv_reslut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        name = findViewById(R.id.name);
        age = findViewById(R.id.age);
        height = findViewById(R.id.height);
        weight = findViewById(R.id.weight);
        married = findViewById(R.id.married);
        save = findViewById(R.id.save);
        read = findViewById(R.id.read);
        save.setOnClickListener(this);
        read.setOnClickListener(this);
        tv_reslut = findViewById(R.id.tv_reslut);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.save:
                String et_name = name.getText().toString();
                String et_age = age.getText().toString();
                String et_height = height.getText().toString();
                String et_weight = weight.getText().toString();

                //拼接字符串
                StringBuilder sb = new StringBuilder();
                sb.append("姓名:").append(et_name);
                sb.append("\n年龄:").append(et_age);
                sb.append("\n身高:").append(et_height);
                sb.append("\n体重:").append(et_weight);
                sb.append("\n婚否:").append(married.isChecked() ? "是" : "否");
                String fileName=System.currentTimeMillis()+".txt";
                String directory=null;
                //外部存储私有空间  应用被卸载就没有了
//                directory=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();

                //外部存储公共空间,相当于手机文件管理,应用卸载还是存在
                directory  = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                path=directory+ File.separator+fileName;
                System.out.println(path);
                FileUtil.saveText(path,sb.toString());
                ToastUtil.show(MainActivity4.this,"保存成功");
                break;
            case R.id.read:
                tv_reslut.setText(FileUtil.openText(path));
                break;
        }
    }
}